{#
/**
 * @file
 * Image placeholder generation.
 *
 * Generates placeholder images and responsive placeholder images based on image configuration.
 */
#}

{#
/**
 * Returns a placeholder image url for an given image style.
 *
 * @return string
 *   The image url.
 */
#}
{% macro get_placeholder_url(image_style, placeholder_url) %}
  {% if not image_style.height %}
    {% set height = random(range(image_style.width * 0.75, image_style.width * 1.25, 10)) %}
  {% endif %}
  {% set img_src = placeholder_url|replace({'[width]': image_style.width, '[height]': image_style.height}) %}
  {{- img_src -}}
{% endmacro %}

{#
/**
 * Prints an image or picture element.
 *
 * @parm string
 *   The image style name.
 * @param object
 *   The image config.
 * @param string
 *   The placeholder service url.
 *
 * @return string
 *   The image.
 */
#}
{% macro image(style, placeholder_url) %}

  {% set imageConfig = pattern_configuration('placeholder', 'image', 'image_config') %}
  {% import _self as self %}
  {% set is_responsive_image = false %}
  {% set image_styles = imageConfig.styles %}
  {% set responsive_image_styles = imageConfig.styles_responsive %}
  {% set breakpoints = imageConfig.breakpoints %}
  {% set image_style = image_styles[style] %}
  {% if image_style is empty %}
    {% set image_style = responsive_image_styles[style] %}
    {% set is_responsive_image = image_style != null ? true : false %}
  {% endif %}

  {# Build responsive image or image. #}
  {% if image_style is empty %}
    No image style {{ style }} found!
  {% else %}
    {% if is_responsive_image == false %}
      <img src="{{- self.get_placeholder_url(image_style, placeholder_url)|trim -}}" alt="A placeholder image">
    {% else %}
      <picture>
        {% for breakpoint_name, image_style_name in image_style.breakpoints %}
          {% if image_styles[image_style_name] is not empty %}
          <source srcset="{{- self.get_placeholder_url(image_styles[image_style_name], placeholder_url) -}}"
                  media="{{ breakpoints[breakpoint_name].mediaQuery }}">
          {% endif %}
        {% endfor %}
        <img src="{{- self.get_placeholder_url(image_styles[image_style.style], placeholder_url)|trim -}}"
             alt="MDN">
      </picture>
    {% endif %}
  {% endif %}
{% endmacro %}

{% macro background(style, classes, placeholder_url) %}
  {% import _self as self %}
  {% set imageConfig = pattern_configuration('placeholder', 'background', 'image_config') %}
  {% set image_styles = imageConfig.styles %}
<div class="{{ classes }}" style="background-image: url('{{ self.get_placeholder_url(image_styles[style], placeholder_url) }}')">
</div>
{% endmacro %}
